const sequelize = require('../config/database');
const logger = require('../utils/logger');

// 导入基础模型
const Role = require('./role');
const PermissionTemplate = require('./PermissionTemplate');
const Department = require('./department');
const User = require('./user');

// 导入关联模型
const UserDepartment = require('./userDepartment');
const UserPermission = require('./userPermission');
const DepartmentPermission = require('./departmentPermission');
const UserThirdParty = require('./userThirdParty');

// 导入其他模型
const SystemConfig = require('./SystemConfig');
const Certificate = require('./Certificate');
const Field = require('./Field');
const Admin = require('./Admin');
const ImportExportRecord = require('./importExportRecord');
const UserLog = require('./userLog');

// 初始化所有模型
const models = {
  // 基础模型
  Role,
  PermissionTemplate,
  Department,
  User,
  
  // 关联模型
  UserDepartment,
  UserPermission,
  DepartmentPermission,
  UserThirdParty,
  
  // 其他模型
  SystemConfig,
  Certificate,
  Field,
  Admin,
  ImportExportRecord,
  UserLog
};

// 同步数据库
const initDatabase = async () => {
  try {
    // 同步所有模型到数据库
    await sequelize.sync({ alter: true });
    logger.info('数据库同步完成');

    // 创建系统预设数据
    await Promise.all([
      Role.createSystemRoles(),
      PermissionTemplate.createSystemTemplates(),
      Department.createRootDepartment(),
      Admin.createInitialAdmin(),
      Field.ensureCertNumberField()
    ]);
    logger.info('系统预设数据创建完成');

  } catch (error) {
    logger.error('数据库初始化失败:', error);
    throw error;
  }
};

module.exports = {
  sequelize,
  ...models,
  initDatabase
}; 